package com.iwown.sample4GApi.controller;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.iwown.sample4GApi.domain.DeviceCallLogs;
import com.iwown.sample4GApi.domain.ResponseObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
@EnableAutoConfiguration
@RequestMapping("/call_log")
public class CallLogController {
    private static final Logger log = LoggerFactory.getLogger(CallLogController.class);
    private static final Gson gson = new Gson();

    @RequestMapping(value = "upload", method = RequestMethod.POST)
    private void uploadSosCallLogData(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        int content_length = req.getContentLength();
        ServletInputStream instream = req.getInputStream();
        byte[] buffer = new byte[content_length];
        int offset = 0;
        while (true){
            int read_size = instream.read(buffer, offset, content_length);
            if(read_size<=0){
                break;
            }
            offset+=read_size;
        }
        instream.close();

        ResponseObject respObj = new ResponseObject();
        String jsonStr = new String(buffer);
        log.info("call log: "+jsonStr);
        try {
            DeviceCallLogs call_log = gson.fromJson(jsonStr, DeviceCallLogs.class);
            respObj.setRetCode(0);
        } catch (JsonSyntaxException ex){
            log.error(ex.getMessage());
            respObj.setRetCode(10002);
        }
        String respStr = gson.toJson(respObj);
        byte[] data = respStr.getBytes();
        resp.getOutputStream().write(data);
        resp.getOutputStream().close();
    }
}
